﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilZ.Dotnet.Ex.Communication.Net.Ftp
{
    internal class FtpCommandManager
    {
        private static readonly Dictionary<string, IFtpCommand> _ftpCommandDic = null;

        static FtpCommandManager()
        {
            Type[] types = typeof(FtpCommandManager).Assembly.GetTypes();
            Type iftpCommandType = typeof(IFtpCommand);
            IFtpCommand command, oldCommand;
            var dic = new Dictionary<string, IFtpCommand>();
            string[] names;

            foreach (var type in types)
            {
                if (!type.IsClass ||
                    type.IsAbstract ||
                    type.GetInterface(iftpCommandType.FullName) == null)
                {
                    continue;
                }

                command = (IFtpCommand)Activator.CreateInstance(type);
                names = command.Names;
                if (names == null || names.Length == 0)
                {
                    throw new ArgumentNullException($"ftp命令类型\"{type.FullName}\"名称为空或null");
                }

                foreach (var name in names)
                {
                    if (dic.TryGetValue(name, out oldCommand))
                    {
                        throw new ArgumentException($"ftp\"类型\"{type.FullName}\"与类型\"{oldCommand.GetType().FullName}\"具有相同的命令名称\"{name}");
                    }

                    dic.Add(name, command);
                }
            }

            _ftpCommandDic = dic;
        }

        public static bool TryGetFtpCommand(string name, out IFtpCommand command)
        {
            return _ftpCommandDic.TryGetValue(name, out command);
        }

        public static IEnumerable<string> GetCommands()
        {
            return _ftpCommandDic.Keys;
        }
    }
}
